package com.example.yoga.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yoga.entity.*;
import com.example.yoga.service.ICardService;
import com.example.yoga.service.IPayRecordService;
import com.example.yoga.service.IUserCardService;
import com.example.yoga.service.IUserService;
import com.example.yoga.util.JsonResult;
import com.example.yoga.util.PageDataResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static org.springframework.context.i18n.LocaleContextHolder.setTimeZone;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liwenkai
 * @since 2021-03-11
 */
@RestController
@RequestMapping("/payRecord")
public class PayRecordController {

    @Autowired
    private IPayRecordService payRecordService;

    @Autowired
    private IUserCardService userCardService;

    @Autowired
    private ICardService cardService;

    @Autowired
    private IUserService userService;


    /**
     * 近五个月的销售总额
     */
    @RequestMapping(value = "/getMoneyByMonth",method = RequestMethod.GET)
    public JsonResult<List> getMoneyByMonth(){
        List<MonthMoney> monthMoneyList = new ArrayList<>();
        //获取每个月，以及每个月的销售金额
        List<MonthMoney> moneyByMonth = payRecordService.getMoneyByMonth();
        System.out.println(moneyByMonth.toString());
//        for (int i = 0; i <moneyByMonth.size(); i++) {
//            MonthMoney monthMoney = new MonthMoney();
//            monthMoney.setMonth(moneyByMonth.get(i).get("month_number")+"月");
//            monthMoney.setMoney((Double) moneyByMonth.get(i).get("money_number"));
//            monthMoneyList.add(monthMoney);
//        }
//        System.out.println(monthMoneyList.toString());
        return new JsonResult<List>(2000,moneyByMonth);
    }

    /**
     * 充值
     * @param userid
     * @param amount
     * @return
     */
    @RequestMapping(value = "/pay",method = RequestMethod.GET)
    public JsonResult<Void> pay(Integer userid, Integer amount){
       //获取用户id,以及充值金额
       //填入充值记录表，生成充值记录编号，记录当前时间，并设置状态为待审批
        //更改系统时间
//        TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8");
//        TimeZone.setDefault(tz);
        //需要进行验证，看该用户下是否有卡，有卡则能进行充值，无可则不能进行充值操作
        QueryWrapper<UserCard> userCardQueryWrapper = new QueryWrapper<>();
        userCardQueryWrapper.eq("userId",userid);
        UserCard one = userCardService.getOne(userCardQueryWrapper);
        if (one==null){
            return new JsonResult<>(4000,"该用户没有卡，不能执行充值操作！");
        }
        PayRecord payRecord = new PayRecord();
        payRecord.setUserid(userid);
        payRecord.setPayno(UUID.randomUUID().toString().replaceAll("-",""));
        payRecord.setPayamount(amount.doubleValue());
        payRecord.setPaydate(new Date());
        payRecord.setPaystatus("待审核");
        //添加该记录
        payRecordService.save(payRecord);
        //找到该用户的卡，将充值的金额设置到卡中
//        QueryWrapper<UserCard> userCardQueryWrapper = new QueryWrapper<>();
//        userCardQueryWrapper.eq("userId",userid);
//        UserCard one = userCardService.getOne(userCardQueryWrapper);
        //通过卡id,得到用户的卡，设置金额
//        Card card = cardService.getById(one.getCardid());
//        BigDecimal decimal = new BigDecimal(amount);
//        BigDecimal totalBalance = decimal.add(card.getBalance());
//        card.setBalance(totalBalance);
        //条件构造器
//        QueryWrapper<Card> cardQueryWrapper = new QueryWrapper<>();
//        cardQueryWrapper.eq("cardId",card.getCardid());
//        //更新数据
//        cardService.update(card,cardQueryWrapper);
        return new JsonResult<>(2000,"充值待审核！");
    }


    /**
     * getPaymentList 获取某个用户的充值记录
     */
    @RequestMapping("/getPaymentList")
    public PageDataResult getPaymentList(Integer userid, Integer pageIndex, Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        QueryWrapper<PayRecord> payRecordQueryWrapper = new QueryWrapper<>();
        payRecordQueryWrapper.eq("userId",userid);
        //获取所有的充值记录
        List<PayRecord> payRecordList = payRecordService.list(payRecordQueryWrapper);
        System.out.println(payRecordList);
        if (payRecordList.size()>0){
            PageInfo<PayRecord> pageInfo = new PageInfo<>(payRecordList);
            PageDataResult pdr = new PageDataResult();
            pdr.setList(pageInfo.getList());
            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
            return pdr;
        }
        return null;
    }


    /**
     * getPayList 获取所有充值记录,用于回显充值记录界面（管理员端）
     */
    @RequestMapping("/getPayList")
    public PageDataResult getPayList(String name, Integer pageIndex, Integer pageSize){
        PageHelper.startPage(pageIndex,pageSize);
        if (name==null||name.length()==0){
            List<PaymentVo> list = payRecordService.getPayList();
            System.out.println(list.toString());
                PageInfo<PaymentVo> pageInfo = new PageInfo<>(list);
                PageDataResult pdr = new PageDataResult();
                pdr.setList(pageInfo.getList());
                pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
                return pdr;
        }
        List<PaymentVo> list = payRecordService.getPayListByName(name);
        PageInfo<PaymentVo> pageInfo = new PageInfo<>(list);
        PageDataResult pdr1 = new PageDataResult();
        pdr1.setList(pageInfo.getList());
        pdr1.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        return pdr1;
//        //先根据姓名查到卡
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("userName",name);
//        User one = userService.getOne(userQueryWrapper);
//        if (one!=null){
//            //找到用户的id
//            QueryWrapper<PayRecord> payRecordQueryWrapper = new QueryWrapper<>();
//            payRecordQueryWrapper.eq("userId",one.getUserid());
//            List<PayRecord> list = payRecordService.list(payRecordQueryWrapper);
//            if (list.size()==0){
//                return null;
//            }
//            PageInfo<PayRecord> pageInfo = new PageInfo<>(list);
//            PageDataResult pdr = new PageDataResult();
//            pdr.setList(pageInfo.getList());
//            pdr.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
//            return pdr;
//        }
    }

    /**
     * ChangeStatus  改变审核充值订单的状态
     */
    @RequestMapping(value = "/ChangeStatus")
    public JsonResult<Void> ChangeStatus(String payno,Integer payamount,Integer userid){
        System.out.println(payno+"..."+payamount+"..."+userid);
        //获取订单编号和充值人id以及充值金额
        //根据充值人id，找出卡id
        QueryWrapper<UserCard> userCardQueryWrapper = new QueryWrapper<>();
        userCardQueryWrapper.eq("userId",userid);
        UserCard one = userCardService.getOne(userCardQueryWrapper);
        //找出这张卡
        Card card = cardService.getById(one.getCardid());
        //改变账户余额
        BigDecimal decimal = new BigDecimal(payamount);
        BigDecimal totalBalance = decimal.add(card.getBalance());
        card.setBalance(totalBalance);
        //条件构造器
        QueryWrapper<Card> cardQueryWrapper = new QueryWrapper<>();
        cardQueryWrapper.eq("cardId",card.getCardid());
        //更新数据
        cardService.update(card,cardQueryWrapper);

        //更改订单记录
        QueryWrapper<PayRecord> payRecordQueryWrapper = new QueryWrapper<>();
        payRecordQueryWrapper.eq("payNo",payno);
        PayRecord payRecord = payRecordService.getOne(payRecordQueryWrapper);
        payRecord.setPaystatus("已审核");
        payRecordService.update(payRecord,payRecordQueryWrapper);
        return new JsonResult<>(2000,"审核完成！");
    }

}

